﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
using Newtonsoft.Json;


public static class TCPClient
{
    private static byte[] data = new byte[4096];
    public static Socket ClientSocket;
    private static Thread receiveT;
    public static Request Request;
    private static AsyncCallback callback;
    public static SocketError Error;

    static TCPClient()
    {
        callback = new AsyncCallback(ReceiveMsg);
        Settings s = ConfigManager.LoadSettings();
        ConnectToServer(s.ServerIP, s.ServerPort);
        Error = SocketError.Success;
    }

    public static bool ConnectToServer(string ip, int port)
    {
        try
        {
            ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            ClientSocket.BeginConnect(IPAddress.Parse(ip), port, callback, null);
            // ClientSocket.Connect(IPAddress.Parse(ip), port);
            // Debug.Log("连接服务器成功" + ip);
            // Thread receiveT = new Thread(ReceiveMsg);
            // receiveT.Start();
            return true;
        }
        catch (System.Exception ex)
        {
            Debug.Log("连接服务器失败！" + ip);
            Debug.Log(ex.Message);
        }
        return false;
    }

    private static void ReceiveMsg(IAsyncResult ar)
    {
        while (true)
        {
            if (!ClientSocket.Connected) { Debug.Log("与服务器断开了连接"); break; }
            if (Error == SocketError.NotConnected) { Debug.Log(Error); }

            int lenght = 0;
            lenght = ClientSocket.Receive(data);

            string json = Encoding.UTF8.GetString(data, 0, lenght);
            Debug.Log(string.Format("From server: {0}", json));
            switch (Request.Operation)
            {
                case Request.GET_ROUND_REQUEST: ConfigManager.DownloadRoundsCallBack(json); continue;
                case Request.GET_RANKING_REQUEST: RankingController.DownloadRankingCallBack(json); continue;
                case Request.ADD_RANKING_REQUEST: break;
                case Request.EXIT_REQUEST: break;
                case Request.NONE_REQUEST: break;
            }
        }
    }

    public static void SendRequest()
    {
        if (!TCPClient.ClientSocket.Connected)
        {
            Settings settings = ConfigManager.LoadSettings();
            TCPClient.ConnectToServer(settings.ServerIP, settings.ServerPort);
        }
        string json = JsonConvert.SerializeObject(Request);
        SendMes(json);
        // if (ClientSocket.Connected)
        // {
        //     string json = JsonConvert.SerializeObject(Request);
        //     SendMes(json);
        //     // Thread receiveT = new Thread(ReceiveMsg);
        //     // receiveT.Start();
        // }
        // else
        // {
        //     Debug.Log("未连接到服务器");
        // }
    }

    private static void SendMes(string ms)
    {
        byte[] data = new byte[1024];
        data = Encoding.UTF8.GetBytes(ms);
        // ClientSocket.Send(data);
        ClientSocket.BeginSend(data, 0, data.Length, SocketFlags.None, out Error, callback, null);
    }

    public static void OnDestroy()
    {
        try
        {
            if (ClientSocket != null)
            {
                ClientSocket.Shutdown(SocketShutdown.Both);
                ClientSocket.Close();//关闭连接
            }

            if (receiveT != null)
            {
                receiveT.Interrupt();
                receiveT.Abort();
            }

        }
        catch (Exception ex)
        {
            Debug.Log(ex.Message);
        }
    }
}